package cn.piggy.gateway.center.interfaces;

import cn.piggy.gateway.center.application.IConfigManageService;
import cn.piggy.gateway.center.application.IMessageService;
import cn.piggy.gateway.center.application.IRegisterManageService;
import cn.piggy.gateway.center.domain.register.model.vo.ApplicationInterfaceMethodVO;
import cn.piggy.gateway.center.domain.register.model.vo.ApplicationInterfaceVO;
import cn.piggy.gateway.center.domain.register.model.vo.ApplicationSystemVO;
import cn.piggy.gateway.center.infrastructure.common.ResponseCode;
import cn.piggy.gateway.center.infrastructure.common.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/wg/admin/register")
public class RpcRegisterManage {

    private final Logger logger = LoggerFactory.getLogger(RpcRegisterManage.class);

    @Resource
    private IRegisterManageService registerManageService;
    @Resource
    private IConfigManageService configManageService;
    @Resource
    private IMessageService messageService;

    @PostMapping(value = "registerApplication", produces = "application/json;charset=utf-8")
    public Result<Boolean> registerApplication(@RequestParam String systemId,
                                               @RequestParam String systemName,
                                               @RequestParam String systemType,
                                               @RequestParam String systemRegistry,
                                               @RequestParam String systemAddress) {
        try {
            logger.info("注册应用服务 systemId：{}", systemId);
            ApplicationSystemVO applicationSystemVO = new ApplicationSystemVO();
            applicationSystemVO.setSystemId(systemId);
            applicationSystemVO.setSystemName(systemName);
            applicationSystemVO.setSystemType(systemType);
            applicationSystemVO.setSystemRegistry(systemRegistry);
            registerManageService.registerApplication(applicationSystemVO);
            return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true);
        } catch (DuplicateKeyException e) {
            logger.warn("注册应用服务重复 systemId：{}", systemId, e);
            return new Result<>(ResponseCode.INDEX_DUP.getCode(), e.getMessage(), true);
        } catch (Exception e) {
            logger.error("注册应用服务失败 systemId：{}", systemId, e);
            return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false);
        }
    }

    @PostMapping(value = "registerApplicationInterface", produces = "application/json;charset=utf-8")
    public Result<Boolean> registerApplicationInterface(@RequestParam String systemId,
                                                        @RequestParam String interfaceId,
                                                        @RequestParam String interfaceName,
                                                        @RequestParam String interfaceVersion) {
        try {
            logger.info("注册应用接口 systemId：{} interfaceId：{}", systemId, interfaceId);
            ApplicationInterfaceVO applicationInterfaceVO = new ApplicationInterfaceVO();
            applicationInterfaceVO.setSystemId(systemId);
            applicationInterfaceVO.setInterfaceId(interfaceId);
            applicationInterfaceVO.setInterfaceName(interfaceName);
            applicationInterfaceVO.setInterfaceVersion(interfaceVersion);
            registerManageService.registerApplicationInterface(applicationInterfaceVO);
            return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true);
        } catch (DuplicateKeyException e) {
            e.printStackTrace();
            logger.warn("注册应用接口重复 systemId：{} interfaceId：{}", systemId, interfaceId);
            return new Result<>(ResponseCode.INDEX_DUP.getCode(), e.getMessage(), true);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("注册应用接口失败 systemId：{}", systemId, e);
            return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false);
        }
    }

    @PostMapping(value = "registerApplicationInterfaceMethod", produces = "application/json;charset=utf-8")
    public Result<Boolean> registerApplicationInterfaceMethod(@RequestParam String systemId,
                                                              @RequestParam String interfaceId,
                                                              @RequestParam String methodId,
                                                              @RequestParam String methodType,
                                                              @RequestParam String parameterType,
                                                              @RequestParam String parameterName,
                                                              @RequestParam String uri,
                                                              @RequestParam String httpCommandType,
                                                              @RequestParam Integer auth,
                                                              @RequestParam String role) {
        try {
            logger.info("注册应用接口方法 systemId：{} interfaceId：{} methodId：{}", systemId, interfaceId, methodId);
            ApplicationInterfaceMethodVO applicationInterfaceMethodVO = new ApplicationInterfaceMethodVO();
            applicationInterfaceMethodVO.setSystemId(systemId);
            applicationInterfaceMethodVO.setInterfaceId(interfaceId);
            applicationInterfaceMethodVO.setMethodId(methodId);
            applicationInterfaceMethodVO.setMethodType(methodType);
            applicationInterfaceMethodVO.setParameterType(parameterType);
            applicationInterfaceMethodVO.setParameterName(parameterName);
            applicationInterfaceMethodVO.setUri(uri);
            applicationInterfaceMethodVO.setHttpCommandType(httpCommandType);
            applicationInterfaceMethodVO.setAuth(auth);
            applicationInterfaceMethodVO.setRole(role);
            registerManageService.registerApplicationInterfaceMethod(applicationInterfaceMethodVO);
            // 推送注册消息
            return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true);
        } catch (DuplicateKeyException e) {
            logger.warn("注册应用接口重复 systemId：{} interfaceId：{}", systemId, interfaceId);
            return new Result<>(ResponseCode.INDEX_DUP.getCode(), e.getMessage(), true);
        } catch (Exception e) {
            logger.error("注册应用接口失败 systemId：{}", systemId, e);
            return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false);
        }
    }

    @PostMapping(value = "registerApplicationInterfaceMethodNew", produces = "application/json;charset=utf-8")
    public Result<Boolean> registerApplicationInterfaceMethodNew(@RequestBody Map<String,Object> map){
        try {
            List<LinkedHashMap<String,Object>> list = (List<LinkedHashMap<String,Object>>)map.get("data");
            for(LinkedHashMap<String,Object> lhm: list){
                ApplicationInterfaceMethodVO applicationInterfaceMethodVO = new ApplicationInterfaceMethodVO();
                applicationInterfaceMethodVO.setSystemId(lhm.get("systemId").toString());
                applicationInterfaceMethodVO.setInterfaceId(lhm.get("interfaceId").toString());
                applicationInterfaceMethodVO.setMethodId(lhm.get("methodId").toString());
                applicationInterfaceMethodVO.setMethodType(lhm.get("methodType").toString());
                applicationInterfaceMethodVO.setParameterType(lhm.get("parameterType").toString());
                applicationInterfaceMethodVO.setParameterName(lhm.get("parameterName").toString());
                applicationInterfaceMethodVO.setUri(lhm.get("uri").toString());
                applicationInterfaceMethodVO.setHttpCommandType(lhm.get("httpCommandType").toString());
                applicationInterfaceMethodVO.setAuth(Integer.parseInt(lhm.get("auth").toString()));
                applicationInterfaceMethodVO.setRole(lhm.get("role").toString());
                registerManageService.registerApplicationInterfaceMethod(applicationInterfaceMethodVO);
            }
            return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true);
        }catch (Exception e){
            e.printStackTrace();
            return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false);
        }
    }

    @PostMapping(value = "registerEvent", produces = "application/json;charset=utf-8")
    public Result<Boolean> registerEvent(@RequestParam String systemId) {
        try {
            logger.info("应用信息注册完成通知 systemId：{}", systemId);
            // 推送注册消息
            List<String> list = configManageService.queryGatewayDistribution(systemId);
            for(String gatewayId : list){
                Map<String,Object> map = new HashMap<>();
                map.put("eventType", "registerEvent");
                map.put("systemId",systemId);
                messageService.pushMessage(gatewayId, map);
            }
            return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true);
        } catch (Exception e) {
            logger.error("应用信息注册完成通知失败 systemId：{}", systemId, e);
            return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false);
        }
    }


    @PostMapping(value = "deleteEvent", produces = "application/json;charset=utf-8")
    public Result<Boolean> deleteEvent(@RequestParam String systemId) {
        try {
            logger.info("应用信息注册完成通知 systemId：{}", systemId);
            // 推送注册消息
            List<String> list = configManageService.queryGatewayDistribution(systemId);
            for(String gatewayId : list){
                Map<String,Object> map = new HashMap<>();
                map.put("eventType", "deleteEvent");
                map.put("systemId",systemId);
                messageService.pushMessage(gatewayId, map);
            }
            return new Result<>(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getInfo(), true);
        } catch (Exception e) {
            logger.error("应用信息注册完成通知失败 systemId：{}", systemId, e);
            return new Result<>(ResponseCode.UN_ERROR.getCode(), e.getMessage(), false);
        }
    }
}
